package com.yq.cp.service.wx.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yq.cp.entity.basics.TotalSettlement;
import com.yq.cp.mapper.basics.TotalSettlementMapper;
import com.yq.cp.service.wx.WxService;
import com.yq.cp.utils.DateTimeUtil;
import com.yq.cp.utils.wx.MyWXPayConfig;
import com.yq.cp.utils.wx.WXPay;
import com.yq.cp.utils.wx.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Service
@Transactional
@Slf4j
public class WxServiceImpl implements WxService {
    @Resource
    TotalSettlementMapper totalSettlementMapper;

    @Override
    public String callback(HttpServletRequest request) {
        try {
            String xml = IOUtils.toString(request.getInputStream(), String.valueOf(StandardCharsets.UTF_8));
            Map<String, String> notifyMap = WXPayUtil.xmlToMap(xml);
            MyWXPayConfig myWXPayConfig = new MyWXPayConfig();
            WXPay wxPay = new WXPay(myWXPayConfig);
            if (wxPay.isPayResultNotifySignatureValid(notifyMap)) {
                // 签名正确
                // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户侧订单状态从退款改成支付成功
                String openId = notifyMap.get("openid");
                //订单号
                String outTradeNo = notifyMap.get("out_trade_no");
                TotalSettlement tradeNo = totalSettlementMapper.selectOne(new QueryWrapper<TotalSettlement>()
                        .eq("out_trade_no", outTradeNo));
                tradeNo.setFeeState(1);
                tradeNo.setFeeType(0);
                tradeNo.setFeeDate(DateTimeUtil.dqsj());
                totalSettlementMapper.updateById(tradeNo);
                //交易号
                String transactionId = notifyMap.get("transaction_id");
                String tradeType = notifyMap.get("trade_type");
                String return_code = notifyMap.get("return_code");
                String result_code = notifyMap.get("result_code");
                if (!"SUCCESS".equals(return_code) || !"SUCCESS".equals(result_code)){
                    return WXPayUtil.NOTIFY_SUCCESS();
                }
                //支付的总金额
                double totalFee = WXPayUtil.fenToYuan(Integer.valueOf(notifyMap.get("total_fee")));

                return WXPayUtil.NOTIFY_SUCCESS();
            } else {
                // 签名错误，如果数据里没有sign字段，也认为是签名错误
//                log.error("签名错误");
                return WXPayUtil.NOTIFY_FAIL("FAIL");
            }
        } catch (Exception e) {
//            log.error("微信回调结果异常,异常原因{}", e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return WXPayUtil.NOTIFY_FAIL(e.getMessage());
        }
    }


}
